/* Includes ------------------------------------------------------------------*/
#include "stm8s.h"
#include "SystemTick.h"
#include "Led.h"
#include "Encoder.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define CHANNEL_A_PORT  (GPIOD)
#define CHANNEL_A_PINS  (GPIO_PIN_3)

#define CHANNEL_B_PORT  (GPIOD)
#define CHANNEL_B_PINS  (GPIO_PIN_2)

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
volatile u32 s_PulseCnt = 0;
u32 s_PulseValue = 0;
u16 s_PrescaleCnt = 0;
u16 s_Prescale = 1000;


/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Public functions ----------------------------------------------------------*/

INTERRUPT_HANDLER(EXTI_PORTD_IRQHandler, 6)
{
    if ((GPIO_ReadInputData(CHANNEL_A_PORT) & CHANNEL_A_PINS) == 0x00)
    {
        s_PulseCnt++;
    }
    //if ((GPIO_ReadInputData(CHANNEL_B_PORT) & CHANNEL_B_PINS) == 0x00)
    //{
        //s_PulseCnt++;
    //}
}

void Encoder_TimerInterrupt(void)
{
    if (s_Prescale <= ++s_PrescaleCnt)
    {
        s_PrescaleCnt = 0;
        
        s_PulseValue = s_PulseCnt;
        s_PulseCnt = 0;
    }
}

void Encoder_Init(void)
{
    GPIO_Init(CHANNEL_A_PORT, CHANNEL_A_PINS, GPIO_MODE_IN_PU_IT);
    GPIO_Init(CHANNEL_B_PORT, CHANNEL_B_PINS, GPIO_MODE_IN_PU_IT);
    
    /* Initialize the Interrupt sensitivity */
    EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOD, EXTI_SENSITIVITY_FALL_ONLY);
    EXTI_SetTLISensitivity(EXTI_TLISENSITIVITY_FALL_ONLY);
    
    SysTick_Registration(&Encoder_TimerInterrupt);
}

u32 Encoder_GetStatus(void)
{
    u32 rc = s_PulseValue;
    s_PulseValue = 0;
    return (rc);
}

void Encoder_SetSampleTimer(u16 iPrescale)
{
    s_Prescale = iPrescale;
}

u16 Encoder_GetSampleTimer(void)
{
    return (s_Prescale);
}
